<template>
  <div class="tag-list">
    <!-- 页面标题 -->
    <el-card
      class="header-card"
      shadow="never"
    >
      <div class="header-row">
        <h2>标签管理</h2>
        <el-button
          type="primary"
          :icon="Plus"
          @click="handleAdd"
        >
          新建标签
        </el-button>
      </div>
    </el-card>

    <!-- 统计卡片 -->
    <el-row
      :gutter="16"
      style="margin-top: 16px"
    >
      <el-col :span="6">
        <el-card
          shadow="hover"
          class="stat-card"
        >
          <el-statistic
            title="标签总数"
            :value="total"
          />
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card
          shadow="hover"
          class="stat-card"
        >
          <el-statistic
            title="启用标签"
            :value="tags.filter(t => t.is_active).length"
          />
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card
          shadow="hover"
          class="stat-card"
        >
          <el-statistic
            title="3星标签"
            :value="tags.filter(t => t.level === 3).length"
          />
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card
          shadow="hover"
          class="stat-card"
        >
          <el-statistic
            title="总使用次数"
            :value="tags.reduce((sum, t) => sum + t.usage_count, 0)"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 筛选区域 -->
    <el-card
      shadow="never"
      style="margin-top: 16px"
    >
      <el-form
        :model="queryParams"
        inline
      >
        <el-form-item label="标签分类">
          <el-select
            v-model="queryParams.category"
            placeholder="请选择分类"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="cat in TAG_CATEGORIES"
              :key="cat.value"
              :label="cat.label"
              :value="cat.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="优先级">
          <el-select
            v-model="queryParams.level"
            placeholder="请选择优先级"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="lv in TAG_LEVELS"
              :key="lv.value"
              :label="lv.label"
              :value="lv.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            :icon="Search"
            @click="handleSearch"
          >
            查询
          </el-button>
          <el-button
            :icon="Refresh"
            @click="handleReset"
          >
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card
      shadow="never"
      style="margin-top: 16px"
    >
      <el-table
        v-loading="loading"
        :data="tags"
        stripe
        border
      >
        <el-table-column
          prop="id"
          label="ID"
          width="80"
        />

        <el-table-column
          prop="name"
          label="标签名称"
          width="150"
        >
          <template #default="{ row }">
            <el-tag :type="getTagColorByCategory(row.category)">
              {{ row.name }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          prop="category"
          label="分类"
          width="120"
        >
          <template #default="{ row }">
            {{ getCategoryLabel(row.category) }}
          </template>
        </el-table-column>

        <el-table-column
          prop="level"
          label="优先级"
          width="120"
        >
          <template #default="{ row }">
            <span>{{ '⭐'.repeat(row.level) }}</span>
          </template>
        </el-table-column>

        <el-table-column
          prop="keywords"
          label="关键词"
          min-width="200"
          show-overflow-tooltip
        />

        <el-table-column
          prop="usage_count"
          label="使用次数"
          width="100"
          align="center"
        />

        <el-table-column
          prop="is_active"
          label="状态"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'info'">
              {{ row.is_active ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          prop="created_at"
          label="创建时间"
          width="180"
        >
          <template #default="{ row }">
            {{ formatDateTime(row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          width="200"
          fixed="right"
        >
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              size="small"
              @click="handleView(row)"
            >
              查看
            </el-button>
            <el-button
              type="primary"
              link
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="queryParams.skip"
          v-model:page-size="queryParams.limit"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSearch"
          @current-change="handleSearch"
        />
      </div>
    </el-card>

    <!-- 新建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="currentTag ? '编辑标签' : '新建标签'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item
          label="标签名称"
          prop="name"
        >
          <el-input
            v-model="formData.name"
            placeholder="请输入标签名称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item
          label="分类"
          prop="category"
        >
          <el-select
            v-model="formData.category"
            placeholder="请选择分类"
            style="width: 100%"
          >
            <el-option
              v-for="cat in TAG_CATEGORIES"
              :key="cat.value"
              :label="cat.label"
              :value="cat.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="优先级"
          prop="level"
        >
          <el-select
            v-model="formData.level"
            placeholder="请选择优先级"
            style="width: 100%"
          >
            <el-option
              v-for="lv in TAG_LEVELS"
              :key="lv.value"
              :label="lv.label"
              :value="lv.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="关键词"
          prop="keywords"
        >
          <el-input
            v-model="formData.keywords"
            type="textarea"
            :rows="3"
            placeholder="请输入关键词，多个关键词用逗号分隔"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item
          label="描述"
          prop="description"
        >
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入标签描述"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item
          label="状态"
          prop="is_active"
        >
          <el-switch
            v-model="formData.is_active"
            active-text="启用"
            inactive-text="停用"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="handleSubmit"
        >
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 详情抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      title="标签详情"
      size="600px"
      direction="rtl"
    >
      <div
        v-if="detailData"
        class="detail-content"
      >
        <el-descriptions
          :column="1"
          border
        >
          <el-descriptions-item label="标签ID">
            {{ detailData.id }}
          </el-descriptions-item>
          <el-descriptions-item label="标签名称">
            <el-tag :type="getTagColorByCategory(detailData.category)">
              {{ detailData.name }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="分类">
            {{ getCategoryLabel(detailData.category) }}
          </el-descriptions-item>
          <el-descriptions-item label="优先级">
            {{ '⭐'.repeat(detailData.level) }} ({{ detailData.level }}星)
          </el-descriptions-item>
          <el-descriptions-item label="关键词">
            {{ detailData.keywords || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="描述">
            {{ detailData.description || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="使用次数">
            {{ detailData.usage_count }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="detailData.is_active ? 'success' : 'info'">
              {{ detailData.is_active ? '启用' : '停用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDateTime(detailData.created_at) }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ formatDateTime(detailData.updated_at) }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'
import {
  getTags,
  createTag,
  updateTag,
  deleteTag,
  getTagColorByCategory,
  TAG_CATEGORIES,
  TAG_LEVELS,
  type Tag,
  type TagCreate,
  type TagUpdate
} from '@/api/tag'
import dayjs from 'dayjs'

// ========== 响应式数据 ==========
const queryParams = reactive({
  category: '',
  level: undefined as number | undefined,
  skip: 0,
  limit: 20,
})

const tags = ref<Tag[]>([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const drawerVisible = ref(false)
const currentTag = ref<Tag | null>(null)
const detailData = ref<Tag | null>(null)
const formRef = ref<FormInstance>()

const formData = reactive<TagCreate>({
  name: '',
  category: 'custom',
  level: 2,
  keywords: '',
  description: '',
  is_active: true,
})

const formRules: FormRules = {
  name: [
    { required: true, message: '请输入标签名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  level: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ],
}

// ========== 方法 ==========

/**
 * 查询列表
 */
const handleSearch = async () => {
  loading.value = true
  try {
    const response = await getTags({
      category: queryParams.category || undefined,
      level: queryParams.level,
      skip: queryParams.skip,
      limit: queryParams.limit,
    })
    tags.value = response.data
    total.value = response.data.length
  } catch (error) {
    ElMessage.error('获取标签列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

/**
 * 重置筛选
 */
const handleReset = () => {
  Object.assign(queryParams, {
    category: '',
    level: undefined,
    skip: 0,
    limit: 20,
  })
  handleSearch()
}

/**
 * 新建标签
 */
const handleAdd = () => {
  currentTag.value = null
  Object.assign(formData, {
    name: '',
    category: 'custom',
    level: 2,
    keywords: '',
    description: '',
    is_active: true,
  })
  dialogVisible.value = true
}

/**
 * 查看详情
 */
const handleView = (row: Tag) => {
  detailData.value = row
  drawerVisible.value = true
}

/**
 * 编辑标签
 */
const handleEdit = (row: Tag) => {
  currentTag.value = row
  Object.assign(formData, {
    name: row.name,
    category: row.category,
    level: row.level,
    keywords: row.keywords || '',
    description: row.description || '',
    is_active: row.is_active,
  })
  dialogVisible.value = true
}

/**
 * 删除标签
 */
const handleDelete = (row: Tag) => {
  ElMessageBox.confirm(`确定要删除标签【${row.name}】吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      await deleteTag(row.id)
      ElMessage.success('删除成功')
      handleSearch()
    } catch (error) {
      ElMessage.error('删除失败')
      console.error(error)
    }
  })
}

/**
 * 提交表单
 */
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (currentTag.value) {
          // 编辑
          const updateData: TagUpdate = {
            name: formData.name,
            category: formData.category,
            level: formData.level,
            keywords: formData.keywords,
            description: formData.description,
            is_active: formData.is_active,
          }
          await updateTag(currentTag.value.id, updateData)
          ElMessage.success('更新成功')
        } else {
          // 新建
          await createTag(formData)
          ElMessage.success('创建成功')
        }
        dialogVisible.value = false
        handleSearch()
      } catch (error: unknown) {
        const axiosError = error as { response?: { data?: { detail?: string } } }
        ElMessage.error(axiosError.response?.data?.detail || '操作失败')
        console.error(error)
      }
    }
  })
}

/**
 * 获取分类标签
 */
const getCategoryLabel = (category: string) => {
  const cat = TAG_CATEGORIES.find(c => c.value === category)
  return cat ? cat.label : category
}

/**
 * 格式化日期时间
 */
const formatDateTime = (datetime: string) => {
  return dayjs(datetime).format('YYYY-MM-DD HH:mm:ss')
}

// ========== 生命周期 ==========
onMounted(() => {
  handleSearch()
})
</script>

<style scoped>
.tag-list {
  padding: 0;
}

.header-card {
  margin-bottom: 0;
}

.header-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-row h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.stat-card {
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.detail-content {
  padding: 16px 0;
}
</style>
